﻿using MediatR;
using Microsoft.EntityFrameworkCore;
using Yuekao.API.Read.Command;
using Yuekao.Domain.API;
using Yuekao.Domain.BaseReposi;
using Yuekao.Domain.Entitys;

namespace Yuekao.API.Read.CommandHandler
{
    /// <summary>
    /// 获取粉丝信息处理器
    /// </summary>
    public class GetFanHandler : IRequestHandler<GetFanCommand, APIPagging<Fan>>
    {
        private readonly IBaseRepository<Fan> _fanRepository;

        public GetFanHandler(IBaseRepository<Fan> fanRepository)
        {
            _fanRepository = fanRepository;
        }
        /// <summary>
        /// 粉丝
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<APIPagging<Fan>> Handle(GetFanCommand request, CancellationToken cancellationToken)
        {
            APIPagging<Fan> res = new APIPagging<Fan>();
            try
            {
                // 构建查询条件
                var query = _fanRepository.GetAll();

                // 添加关键词搜索条件（用户名或账号模糊查询）
                if (!string.IsNullOrEmpty(request.Keyword))
                {
                    string keyword = request.Keyword.Trim();
                    query = query.Where(x => x.Account.Contains(keyword) || x.AccountName.Contains(keyword));
                }

                // 添加创建时间条件（按日期查询，忽略时间部分）
                if (request.CreateTime.HasValue)
                {
                    var targetDate = request.CreateTime.Value.Date;
                    query = query.Where(x => x.CreateTime.Date == targetDate);
                }

                // 获取总数
                res.TotaCount = query.Count();

                // 计算总页数
                res.TotaSize = (int)Math.Ceiling(res.TotaCount * 1.0 / request.PageSize);

                // 分页查询数据（按创建时间倒序，然后按ID倒序）
                                    res.PageData = query
                        .OrderByDescending(x => x.CreateTime)
                        .ThenByDescending(x => x.FanId)
                        .Skip((request.PageIndex - 1) * request.PageSize)
                        .Take(request.PageSize)
                        .ToList();

                    res.Code = APIEnum.Success;   
                    res.Message = $"查询成功，共找到 {res.TotaCount} 条记录";
                    res.Data = res.PageData.FirstOrDefault(); // 设置Data属性为第一个元素或默认值
            }
            catch (Exception ex)
            {
                res.Code = APIEnum.Fail;
                res.Message = $"查询粉丝信息失败: {ex.Message}";
                res.PageData = new List<Fan>();
                res.Data = null; // 设置Data属性为null
            }

            return res;
        }

       

       
    }
}
